package com.dhl.springbootrabbitmq.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.sql.SQLOutput;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Administrator
 * 使用rabbitMQ插件实现延时消息发送
 */
@Configuration
public class DelayedTtlQueueConfig {
    /**
     * 延迟交换机
     */
    public static final String DELAYED_EXCHANGE = "delayed_exchange";
    /**
     * 延迟对列
     */
    public static final String DELAYED_QUEUE = "delayed_queue";
    /**
     * routingKey
     */
    public static final String DELAYED_ROUTING_KEY = "delayed_routing_key";
    /**
     * 延迟交换的TYPE
     */
    public static final String X_DELAYED_MESSAGE = "x-delayed-message";

    /**
     * 声明延迟交换
     *
     * @return
     */
    @Bean
    public CustomExchange delayExchange() {
        Map<String, Object> map = new HashMap<>(1);
        map.put("x-delayed-type", ExchangeTypes.DIRECT);
        /**
         * 1:交换名称
         * 2：交换类别
         * 3：是否持久化
         * 4：是否自动删除
         * 5：其他参数
         */
        CustomExchange customExchange = new CustomExchange(DELAYED_EXCHANGE, X_DELAYED_MESSAGE, true, false, map);
        return customExchange;
    }
//    @Bean
//    public DirectExchange delayDirectExchange() {
//        return ExchangeBuilder.directExchange(DELAYED_EXCHANGE).delayed().build();
//    }

    /**
     * 声明队列
     *
     * @return
     */
    @Bean
    public Queue delayQueue() {
        return QueueBuilder.durable(DELAYED_QUEUE).build();
    }

    /**
     * 队列绑定交换
     *
     * @param delayQueue          延迟队列
     * @param delayExchange 延迟交换
     * @return
     */
    @Bean
    public Binding delayQueueBindingDelayExchange(Queue delayQueue, CustomExchange delayExchange) {
        return BindingBuilder.bind(delayQueue).to(delayExchange).with(DELAYED_ROUTING_KEY).noargs();
    }

}
